package com.cray.intelligenthydrologyback.interceptor;

import com.cray.intelligenthydrologyback.client.request.LoginRequest;
import com.cray.intelligenthydrologyback.client.response.LoginResponse;
import com.cray.intelligenthydrologyback.config.GlobalConfig;
import org.springframework.context.ApplicationContext;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.HandlerInterceptor;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Emil
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private GlobalConfig globalConfig;
    private final WebClient.Builder webClientBuilder;

    @Autowired
    private ApplicationContext applicationContext;

    public TokenInterceptor(WebClient.Builder webClient) {
        this.webClientBuilder = webClient;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) {
        System.out.println("Interceptor - request per handle");

        // Build request
        LoginRequest loginRequest = LoginRequest.builder()
                .username("admin")
                .password("admin123")
                .build();

        LoginResponse loginResponse = webClientBuilder.build().post()
                .uri("/login")
                .bodyValue(loginRequest) // 设置请求体
                .retrieve()
                .onStatus(HttpStatus::isError, clientResponse ->
                        Mono.error(new RuntimeException("Failed to call API"))
                )
                .bodyToMono(LoginResponse.class)
                .block();

        if (ObjectUtils.isNotEmpty(loginResponse)) {
            globalConfig.setToken(loginResponse.getToken());

            WebClient.Builder webclientBuilder = applicationContext.getBean(WebClient.Builder.class);
            webclientBuilder.defaultHeader("Authorization", globalConfig.getToken()); // 可添加通用 Header
        }
        // 返回 true 表示继续处理，返回 false 会中断请求
        return true;
    }
}
